package x.cribug.app.moudles.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import x.cribug.app.common.util.session.SessionUtil;
import x.cribug.app.moudles.mapper.UserMapper;
import x.cribug.app.moudles.service.UserService;
import x.cribug.common.entity.app.form.UpdateUserForm;
import x.cribug.common.entity.app.User;
import x.cribug.common.common.exception.ServiceException;
import x.cribug.common.service.RedisService;
import x.cribug.common.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private WeixinService weixinService;

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisService redisService;


    // 通过微信登录，没有就注册
    @Transactional
    @Override
    public User loginByWeixin(String code) throws ServiceException {
        String wxOpenid = weixinService.getWeiXinOpenid(code);
        if (wxOpenid != null) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("open_id", wxOpenid);
            User user = userMapper.selectOne(userQueryWrapper);
            if (user == null) { // 没有就注册
                user = new User();
                user.setOpenId(wxOpenid);
                userMapper.insert(user);
            }

            SessionUtil.setUserSession(user);
            return user;
        } else {
            throw ServiceException.CONST_wx_login_failed;
        }
    }

    @Override
    public User getUser(String wxOpenid) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("open_id", wxOpenid);
        return userMapper.selectOne(userQueryWrapper);
    }

    @Override
    public Object updateUser(UpdateUserForm form, String openid) throws Exception {
        User user = new User();
        System.out.println(form.toString());
        user.setId(form.getId());
        user.setOpenId(openid);
        user.setNickName(form.getNickName());
        user.setAvatarUrl(form.getAvatarUrl());
        user.setCity(form.getCity());
        user.setCountry(form.getCountry());
        user.setProvince(form.getProvince());
        user.setGender(form.getGender());
        user.setEmail(form.getEmail());
        user.setLastVisitTime(new Date());
        return userMapper.updateById(user) > 0 ? getUser(user.getOpenId()) : null;
    }
}
